import * as cloud from 'wx-server-sdk';

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV as unknown as string
})
const db = cloud.database()
const _ = db.command

enum LedTaskExecutedStatus {
  Wait = 0,
  Success = 1,
}
const MAX_LIMIT = 100

exports.main = async (_event: any, _context: any) => {
  const { } = _event
  const now = new Date().getTime()
  let a = db.collection('LedTask').where({
    executedStatus: LedTaskExecutedStatus.Wait,
    changeTime: _.and([
      _.lt(new Date(now + 60 * 1000)),
      _.gt(new Date(now - 60 * 1000))
    ])
  })
  let b = await a.count({}) as cloud.DB.ICountResult

  if (b.total > 0) {
    const batchTimes = Math.ceil(b.total / MAX_LIMIT)

    for (let i = 0; i < batchTimes; i++) {
      let c = await a.field({
        speed: true,
        ledtext: true,
        count: true,
        deviceId: true,
      }).skip(i * MAX_LIMIT).limit(MAX_LIMIT).get() as cloud.DB.IQueryResult
      console.log("get", c);
      let e = [] as Promise<cloud.ICloud.CallFunctionResult>[]
      for (let index = 0; index < c.data.length; index++) {
        const element = c.data[index];
        e.push(cloud.callFunction({
          // 要调用的云函数名称
          name: 'WeMqttApi',
          // 传递给云函数的参数
          data: {
            data: {
              speed: element.speed,
              text: element.ledtext,
              count: element.count
            },
            deviceName: element.deviceId,
            eventCode: 'SendText'
          }
        }) as Promise<cloud.ICloud.CallFunctionResult>)
      }
      await Promise.all(e)
    }

    let d = await a.update({
      data: {
        executedStatus: LedTaskExecutedStatus.Success
      }
    }) as cloud.DB.IUpdateResult
    console.log("update", d);
  }

  return null
}
/**
 *
 * now = 10045
 *
 * set = 10000
 *
 * now > set
 * now < set + 500
 */